Unit I - Lectures 4 & 5
BTech 4th Semester
UPES - University of Petroleum and Energy Studies
Instructor: Mohsin Dar
Java provides several methods to display output to the console:
Prints text without adding a new line at the end.
System.out.print("Hello ");
System.out.print("World");
// Output: Hello World
Prints text and moves cursor to the next line.
System.out.println("Hello");
System.out.println("World");
// Output:
// Hello
// World
The Scanner class is used to get user input from various sources.
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.println("Hello " + name);
System.out.println("You are " + age + " years old");
sc.close();
}
}
| Method | Description | Return Type |
|---|---|---|
| nextInt() | Reads an integer value | int |
| nextDouble() | Reads a double value | double |
| nextFloat() | Reads a float value | float |
| next() | Reads a single word (till space) | String |
| nextLine() | Reads a complete line | String |
| nextBoolean() | Reads a boolean value | boolean |
Command line arguments allow you to pass information to a program when it starts executing.
Arguments passed to the program at runtime through the command line interface.
public class CommandLineExample {
public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
for(int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
}
}
java CommandLineExample Hello World 123
public class Calculator {
public static void main(String[] args) {
if(args.length < 2) {
System.out.println("Please provide two numbers");
return;
}
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int sum = num1 + num2;
System.out.println("Sum: " + sum);
}
}
// Execution: java Calculator 10 20
// Output: Sum: 30
Java is a strongly typed language. Every variable must have a data type.
Basic data types built into the Java language (8 types)
Reference types like Classes, Interfaces, Arrays, Strings
| Data Type | Size | Range | Default Value |
|---|---|---|---|
| byte | 1 byte | -128 to 127 | 0 |
| short | 2 bytes | -32,768 to 32,767 | 0 |
| int | 4 bytes | -2³¹ to 2³¹-1 | 0 |
| long | 8 bytes | -2⁶³ to 2⁶³-1 | 0L |
| float | 4 bytes | ±3.4e-038 to ±3.4e+038 | 0.0f |
| double | 8 bytes | ±1.7e-308 to ±1.7e+308 | 0.0d |
| char | 2 bytes | 0 to 65,535 (Unicode) | '\u0000' |
| boolean | 1 bit | true or false | false |
public class DataTypesDemo {
public static void main(String[] args) {
// Integer types
byte age = 25;
short year = 2024;
int population = 1400000000;
long distance = 9876543210L; // L suffix for long
// Floating-point types
float price = 99.99f; // f suffix for float
double pi = 3.14159265359;
// Character type
char grade = 'A';
char symbol = '\u0041'; // Unicode for 'A'
// Boolean type
boolean isPassed = true;
boolean isRaining = false;
System.out.println("Age: " + age);
System.out.println("Grade: " + grade);
System.out.println("Passed: " + isPassed);
}
}
A variable is a named memory location that stores a value.
dataType variableName;
dataType variableName = value;
Declared inside methods, constructors, or blocks. Must be initialized before use.
Declared inside a class but outside methods. Each object has its own copy.
Declared with static keyword. Shared among all instances of a class.
public class VariablesDemo {
// Instance variable
int instanceVar = 10;
// Static variable
static int staticVar = 20;
public void display() {
// Local variable
int localVar = 30;
System.out.println("Instance Variable: " + instanceVar);
System.out.println("Static Variable: " + staticVar);
System.out.println("Local Variable: " + localVar);
}
public static void main(String[] args) {
VariablesDemo obj1 = new VariablesDemo();
VariablesDemo obj2 = new VariablesDemo();
obj1.instanceVar = 100; // Only obj1's copy changes
staticVar = 200; // Shared by all objects
obj1.display();
obj2.display();
}
}
// Valid variable names
int age;
int student_age;
int $price;
int _count;
// Invalid variable names
int 2students; // Cannot start with digit
int student-age; // Cannot use hyphen
int class; // Cannot use keyword
Operators are special symbols that perform specific operations on operands.
| Operator | Name | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 5 - 3 | 2 |
| * | Multiplication | 5 * 3 | 15 |
| / | Division | 10 / 3 | 3 (integer division) |
| % | Modulus (Remainder) | 10 % 3 | 1 |
int a = 10, b = 3;
System.out.println("Addition: " + (a + b)); // 13
System.out.println("Subtraction: " + (a - b)); // 7
System.out.println("Multiplication: " + (a * b)); // 30
System.out.println("Division: " + (a / b)); // 3
System.out.println("Modulus: " + (a % b)); // 1
Used to compare two values. Returns boolean result (true or false).
| Operator | Name | Example | Result |
|---|---|---|---|
| == | Equal to | 5 == 3 | false |
| != | Not equal to | 5 != 3 | true |
| > | Greater than | 5 > 3 | true |
| < | Less than | 5 < 3 | false |
| >= | Greater than or equal to | 5 >= 5 | true |
| <= | Less than or equal to | 5 <= 3 | false |
Used to combine multiple conditions.
| Operator | Name | Description | Example |
|---|---|---|---|
| && | Logical AND | Returns true if both conditions are true | (5 > 3) && (8 > 5) → true |
| || | Logical OR | Returns true if at least one condition is true | (5 > 3) || (8 < 5) → true |
| ! | Logical NOT | Reverses the boolean value | !(5 > 3) → false |
int age = 20;
boolean hasLicense = true;
// AND operator
if(age >= 18 && hasLicense) {
System.out.println("You can drive");
}
// OR operator
if(age < 18 || !hasLicense) {
System.out.println("You cannot drive");
}
| Operator | Example | Equivalent to |
|---|---|---|
| = | x = 5 | x = 5 |
| += | x += 3 | x = x + 3 |
| -= | x -= 3 | x = x - 3 |
| *= | x *= 3 | x = x * 3 |
| /= | x /= 3 | x = x / 3 |
| %= | x %= 3 | x = x % 3 |
int num = 10;
num += 5; // num = 15
num -= 3; // num = 12
num *= 2; // num = 24
num /= 4; // num = 6
num %= 4; // num = 2
System.out.println("Final value: " + num); // 2
Operators that work with a single operand.
| Operator | Name | Description |
|---|---|---|
| ++ | Increment | Increases value by 1 |
| -- | Decrement | Decreases value by 1 |
| + | Unary plus | Indicates positive value |
| - | Unary minus | Negates an expression |
| ! | Logical NOT | Inverts boolean value |
int a = 5;
int b = ++a; // Pre-increment: a becomes 6, then b = 6
System.out.println("a: " + a + ", b: " + b); // a: 6, b: 6
int c = 5;
int d = c++; // Post-increment: d = 5, then c becomes 6
System.out.println("c: " + c + ", d: " + d); // c: 6, d: 5
A shorthand way to write if-else statements. Also called the conditional operator.
variable = (condition) ? expressionTrue : expressionFalse;
int age = 20;
String result = (age >= 18) ? "Adult" : "Minor";
System.out.println(result); // Output: Adult
// Traditional if-else equivalent:
String result2;
if(age >= 18) {
result2 = "Adult";
} else {
result2 = "Minor";
}
// Finding maximum of two numbers
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println("Maximum: " + max); // 20
Determines the order in which operators are evaluated in an expression.
| Precedence | Operator | Description |
|---|---|---|
| 1 (Highest) | ++, -- | Postfix increment/decrement |
| 2 | ++, --, +, -, ! | Unary operators |
| 3 | *, /, % | Multiplicative |
| 4 | +, - | Additive |
| 5 | <, <=, >, >= | Relational |
| 6 | ==, != | Equality |
| 7 | && | Logical AND |
| 8 | || | Logical OR |
| 9 | ?: | Ternary |
| 10 (Lowest) | =, +=, -=, *=, /=, %= | Assignment |
int result;
// Example 1: Multiplication before addition
result = 5 + 3 * 2;
System.out.println(result); // Output: 11 (not 16)
// Explanation: 3 * 2 = 6, then 5 + 6 = 11
// Example 2: Using parentheses to change precedence
result = (5 + 3) * 2;
System.out.println(result); // Output: 16
// Explanation: 5 + 3 = 8, then 8 * 2 = 16
// Example 3: Complex expression
result = 10 + 5 * 2 - 3 / 3;
System.out.println(result); // Output: 19
// Step 1: 5 * 2 = 10
// Step 2: 3 / 3 = 1
// Step 3: 10 + 10 - 1 = 19
// Example 4: Relational and logical operators
boolean flag = 5 > 3 && 10 < 20 || 8 == 8;
System.out.println(flag); // Output: true
Converting a value from one data type to another.
Automatic conversion from smaller to larger data type. No data loss.
int num = 100;
long bigNum = num; // int to long
float decimal = bigNum; // long to float
double precise = decimal; // float to double
System.out.println(precise); // 100.0
Manual conversion from larger to smaller data type. May cause data loss.
double d = 99.99;
int i = (int) d; // Explicit casting required
System.out.println(i); // Output: 99 (decimal part lost)
long l = 1000000L;
int j = (int) l;
System.out.println(j); // Output: 1000000
import java.util.Scanner;
public class StudentGradeCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input
System.out.print("Enter student name: ");
String name = sc.nextLine();
System.out.print("Enter marks in Math: ");
int mathMarks = sc.nextInt();
System.out.print("Enter marks in Science: ");
int scienceMarks = sc.nextInt();
System.out.print("Enter marks in English: ");
int englishMarks = sc.nextInt();
// Calculations
int total = mathMarks + scienceMarks + englishMarks;
double average = total / 3.0;
// Grade determination using ternary operator
char grade = (average >= 90) ? 'A' :
(average >= 80) ? 'B' :
(average >= 70) ? 'C' :
(average >= 60) ? 'D' : 'F';
// Output
System.out.println("\n--- Student Report ---");
System.out.println("Name: " + name);
System.out.println("Total Marks: " + total + "/300");
System.out.println("Average: " + average + "%");
System.out.println("Grade: " + grade);
sc.close();
}
}
What will be the output of the following code?
int x = 10;
int y = x++ + ++x;
System.out.println("x: " + x + ", y: " + y);
Write a program that takes two numbers as command line arguments and displays their sum, difference, product, and quotient.
What is the difference between == and = operators?
Explain the difference between int division and double division with an example.
Create a program using Scanner class that takes student's marks in 5 subjects and calculates percentage and grade.
Instructor: Mohsin Dar
BTech 4th Semester - OOP using Java
UPES